package com.example.blogdesign.Service.Impl;


import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.blogdesign.Entity.Blog;
import com.example.blogdesign.Entity.BlogComments;

import com.example.blogdesign.Entity.User;
import com.example.blogdesign.Mapper.BlogCommentsMapper;
import com.example.blogdesign.Service.IBlogCommentsService;
import com.example.blogdesign.Service.IBlogService;
import com.example.blogdesign.Service.IUserService;
import com.example.blogdesign.dto.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;


@Service
public class BlogCommentsServiceImpl extends ServiceImpl<BlogCommentsMapper, BlogComments> implements IBlogCommentsService {

    @Resource
    private IBlogService blogService;

    @Resource
    private IUserService userService;

    @Transactional
    @Override
    public Result<?> addBlogComments(BlogComments blogComments) {
        //保存博客评论
        save(blogComments);
        //博客评论数+1
        blogService.update().setSql("comments=comments+1").eq("id",blogComments.getBlogId()).update();
        return Result.ok("新增成功");
    }

    @Override
    public Result<List<BlogComments>> queryAnswerComments(Long blogCommentId) {
        List<BlogComments> blogCommentsList = query().eq("parent_id", blogCommentId).list();
        queryBlogCommentsUserName(blogCommentsList);
        return Result.ok(blogCommentsList);
    }


    //查询一级评论
    @Override
    public Result<List<BlogComments>> queryBlogFirstComments(Long blogId) {
        List<BlogComments> blogCommentsList = query().eq("blog_id", blogId).eq("parent_id",0).list();
        queryBlogCommentsUserName(blogCommentsList);
        return Result.ok(blogCommentsList);
    }


    private void queryBlogCommentsUserName(List<BlogComments> blogCommentsList) {
        for (BlogComments blogComment:blogCommentsList) {
            Long userId = blogComment.getUserId();
            User user = userService.getById(userId);
            blogComment.setName(user.getNickName());
        }
    }


}
